/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "hhdMessenger.h"
#include "hhdIMessage.h"
#include "hhdIMessageReceiver.h"
#include "hhdIMessageSender.h"

namespace hhd
{
    namespace hhdMessenger
    {
        void sendMessage(IMessage* in_message, IMessageReceiver* in_receiver)
        {
            Messenger::sendMessage(in_message, in_receiver);
        }

        void forwardMessage(IMessage* in_message, IMessageReceiver* in_receiver)
        {
            Messenger::forwardMessage(in_message, in_receiver);
        }
    }


    Vector<IMessageReceiver*>* Messenger::_receiver_buffer_0 = NULL;
    Vector<IMessageReceiver*>* Messenger::_receiver_buffer_1 = NULL;
    HashSet<void*>* Messenger::_receiver_set_0 = NULL;
    HashSet<void*>* Messenger::_receiver_set_1 = NULL;
    ArrayList<IMessage*>* Messenger::_message_buffer = NULL;
    HashSet<void*>* Messenger::_message_set = NULL;

    Mutex Messenger::_receiver_buffer_lock;
    Mutex Messenger::_receiver_set_lock;
    Mutex Messenger::_message_buffer_lock;
    Mutex Messenger::_message_set_lock;

    void Messenger::initialize()
    {
        _receiver_buffer_0 = new Vector<IMessageReceiver*>();
        _receiver_buffer_1 = new Vector<IMessageReceiver*>();
        _receiver_set_0 = new HashSet<void*>();
        _receiver_set_1 = new HashSet<void*>();
        _message_buffer = new ArrayList<IMessage*>();
        _message_set = new HashSet<void*>();
    }

    void Messenger::finalize()
    {
        delete _receiver_buffer_0;
        delete _receiver_buffer_1;
        delete _receiver_set_0;
        delete _receiver_set_1;
        delete _message_buffer;
        delete _message_set;
    }

    void Messenger::handleMessages()
    {
        while(_receiver_buffer_0->size() > 0)
        {
            // swap receiver buffers
            Vector<IMessageReceiver*>* temp_buffer = _receiver_buffer_0;
            _receiver_buffer_0 = _receiver_buffer_1;
            _receiver_buffer_1 = temp_buffer;
            // swap receiver sets
            HashSet<void*>* temp_set = _receiver_set_0;
            _receiver_set_0 = _receiver_set_1;
            _receiver_set_1 = temp_set;

            // clear the buffer
            _receiver_buffer_0->clear();
            _receiver_set_0->clear();

            // swap receiver queues so that messages sent here don't get sent to handling queue
            for(size_t k = 0; k < _receiver_buffer_1->size(); k++)
            {
                (*_receiver_buffer_1)[k]->swapQueues();
            }

            for(size_t k = 0; k < _receiver_buffer_1->size(); k++)
            {
                (*_receiver_buffer_1)[k]->handleMessages();
            }
        }

        // release messages to factory
        for(size_t k = 0; k < _message_buffer->size(); k++)
        {
            Factory::release(_message_buffer->get(k));
        }
        _message_buffer->clear();
        _message_set->clear();

    }

    void Messenger::sendMessage(IMessage* message, IMessageReceiver* receiver)
    {
        if(receiver != NULL)
        {
            // see if the receiver is in our list and add if not
//				_receiver_set_lock.lock();
            if(_receiver_set_0->add(receiver))
            {
//					_receiver_set_lock.unlock();
//					_receiver_buffer_lock.lock();
                _receiver_buffer_0->add(receiver);
//					_receiver_buffer_lock.unlock();
            }
            else
            {
//					_receiver_set_lock.unlock();
            }
            // give receiver the message (this method is synchronized)
            receiver->enqueueMessage(message);
        }

        // cache the message for memory management
//			_message_set_lock.lock();
        if(_message_set->add(message))
        {
//				_message_set_lock.unlock();
//				_message_buffer_lock.lock();
            _message_buffer->add(message);
//				_message_buffer_lock.unlock();
        }
        else
        {
//				_message_set_lock.unlock();
        }
    }

    void Messenger::forwardMessage(IMessage* message, IMessageReceiver* receiver)
    {
        if(receiver != NULL)
        {
            // see if the receiver is in our list and add if not
//				_receiver_set_lock.lock();
            if(_receiver_set_0->add(receiver))
            {
//					_receiver_set_lock.unlock();
//					_receiver_buffer_lock.lock();
                _receiver_buffer_0->add(receiver);
//					_receiver_buffer_lock.unlock();
            }
            else
            {
//					_receiver_set_lock.unlock();
            }
            // give receiver the message (this method is synchronized)
            receiver->enqueueMessage(message);
        }
        // don't cachemessage for memory management
    }

    void Messenger::clearReceivers(IMessageSender* in_sender)
    {
        // basically have to clear _receiver_index here
        IEnumerator < Pair<int, Vector<IMessageReceiver*>* > >* iter = in_sender->_receiver_index->getNewEnumerator();
        while(iter->moveNext())
        {
            Pair<int, Vector<IMessageReceiver*>* >& p = iter->current();
            Vector<IMessageReceiver*>* receiver_list = p.second;
            for(size_t k = 0; k < receiver_list->size(); k++)
            {
                receiver_list->get(k)->_senders->remove(Pair<int,IMessageSender*>(p.first, in_sender));
            }
        }

        delete iter;
    }
}
